#include<wiringPi.h>
#include<string.h>
#include<stdio.h>
#include <sys/time.h>
#include <unistd.h>

#define CSB_TRIG 	  0
#define CSB_ECHO 	  1

// csb
double getDistance()
{
    double dis ;
    // csb pin脚初始化
    pinMode(CSB_TRIG, OUTPUT);
    pinMode(CSB_ECHO, INPUT);

    struct timeval start;
    struct timeval stop;

    // 激活功能
    digitalWrite(CSB_TRIG, LOW);
    usleep(5);
    digitalWrite(CSB_TRIG, HIGH);
    usleep(10);
    digitalWrite(CSB_TRIG, LOW);
    
    usleep(100);
    // 模块内部初始化

    //printf("01:digitalRead(CSB_ECHO) = %d\n", digitalRead(CSB_ECHO));
    while(digitalRead(CSB_ECHO) != 1);
    //printf("02:digitalRead(CSB_ECHO) = %d\n", digitalRead(CSB_ECHO));
    gettimeofday(&start, NULL);
    while (digitalRead(CSB_ECHO) != 0);
    //printf("03:digitalRead(CSB_ECHO) = %d\n", digitalRead(CSB_ECHO));
    gettimeofday(&stop, NULL);

    // us
    long time_diff =
        1000000 * (stop.tv_sec - start.tv_sec) + (stop.tv_usec - start.tv_usec);

    // cm
    dis = (double)time_diff / 1000000 * 34000 / 2;
    return dis;
}
